#include <stdio.h>
#include <signal.h>
#include "workflow/WFFacilities.h"
#include "workflow/WFHttpServer.h"
#include "slre.h"

int main(int argc, char **argv)
{
    static WFFacilities::WaitGroup wait_group(1);
    signal(SIGINT, [](int signo)
    {
        wait_group.done();
    });

    WFHttpServer server([](WFHttpTask *task)
    {
        protocol::HttpRequest *req = task->get_req();
        protocol::HttpResponse *resp = task->get_resp();
        long long seq = task->get_task_seq();
        char buf[8192];
        int len;
        const char *pUri = "/a.mbtiles/3/4/5.png";//req->get_request_uri();
        struct slre_cap caps[4];

        //memset(caps, 0, sizeof(caps));
        if (slre_match("^/([a-zA-Z0-9]+).mbtiles/(\\d+)/(\\d+)/(\\d+).png",
                   pUri, strlen(pUri), caps, 4, 0) > 0) {
            //printf("Method: [%.*s], URI: [%.*s]\n",
            // caps[0].len, caps[0].ptr,
            // caps[1].len, caps[1].ptr);
        }
    
        /* Set response message body. */
        resp->append_output_body_nocopy("<html>", 6);
        len = snprintf(buf, 8192, "<p>%s %s %s</p><p>%.*s %.*s %.*s %.*s</p>", req->get_method(), req->get_request_uri(), req->get_http_version(),
          caps[0].len, caps[0].ptr, caps[1].len, caps[1].ptr, caps[2].len, caps[2].ptr, caps[3].len, caps[3].ptr);
        resp->append_output_body(buf, len);
        resp->append_output_body_nocopy("</html>", 7);

        /* Set status line if you like. */
        resp->set_http_version("HTTP/1.1");
        resp->set_status_code("200");
        resp->set_reason_phrase("OK");
        resp->add_header_pair("Content-Type", "text/html");
        resp->add_header_pair("Server", "Sogou WFHttpServer");
    });

    if (server.start(8888) == 0)
    {
        wait_group.wait();
        server.stop();
    }
    else
    {
        perror("Cannot start server");
        exit(1);
    }

    return 0;
}

